export default {
    inserted(el, binding) {
        if (typeof window === 'undefined' || typeof IntersectionObserver === 'undefined') {
            el.style.opacity = 1
            el.style.transform = 'none'
            return
        }

        // 动画类型（默认 fade-up）
        const type = typeof binding.value === 'string' ? binding.value : 'fade-up'

        // 不同类型的初始样式
        const animationMap = {
            'fade-up':    { from: 'translateY(30px)', to: 'translateY(0)' },
            'fade-down':  { from: 'translateY(-30px)', to: 'translateY(0)' },
            'slide-left': { from: 'translateX(-40px)', to: 'translateX(0)' },
            'slide-right':{ from: 'translateX(40px)', to: 'translateX(0)' },
            'zoom-in':    { from: 'scale(0.8)', to: 'scale(1)' },
            'blur-in':    { from: 'scale(1) blur(10px)', to: 'scale(1) blur(0)' },
        }

        const anim = animationMap[type] || animationMap['fade-up']

        // 初始状态
        el.style.opacity = 0
        el.style.transform = anim.from
        el.style.transition = 'all 0.8s ease-out'
        el.style.willChange = 'opacity, transform, filter'

        // IntersectionObserver 逻辑
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    el.style.opacity = 1
                    // 支持 blur 的用 filter
                    if (type === 'blur-in') {
                        el.style.filter = 'blur(0)'
                    }
                    el.style.transform = anim.to
                    observer.unobserve(el)
                }
            })
        }, { threshold: 0.2 })

        observer.observe(el)
        el._scrollObserver = observer
    },

    unbind(el) {
        if (el._scrollObserver) {
            el._scrollObserver.disconnect()
            delete el._scrollObserver
        }
    }
}
